﻿#include "application.h"
#include "settings.h"

#include <QFile>
#include <QLocalSocket>
#include <QSettings>
#include <QTimer>
#include <QDir>
const QString SERVER_NAME = QString("com.casstime.desktop.remind");

Application::Application(int argc, char **argv)
    :QApplication(argc,argv)
{
    QDir::setCurrent(this->applicationDirPath());

    QLocalSocket socket;
    socket.connectToServer(SERVER_NAME);

    //如果已有实例启动，则自己退出
    if(socket.waitForConnected(1000)){
         QTimer::singleShot(0, this, SLOT(quit()));
    }

    //监听
    server = new QLocalServer(this);
    connect(server,SIGNAL(newConnection()),this,SLOT(newLocalConnection()));
    if(server->listen(SERVER_NAME)){
        //防止程序崩溃时,残留进程服务,移除之
        if(server->serverError()==QAbstractSocket::AddressInUseError && QFile::exists(server->serverName()))
        {
            QFile::remove(server->serverName());
            server->listen(SERVER_NAME);
        }
    }
    Settings *settings = Settings::getInstance();
    QString appName = settings->getAppName();
    QString appVersion = settings->getAppVersion();
    this->setApplicationDisplayName(appName);
    this->setApplicationName(appName);
    this->setApplicationVersion(appVersion);


    //即使所有窗口关闭也不退出程序
    this->setQuitOnLastWindowClosed(false);

    //加载样式
    this->loadStylesheet();

}

void Application::loadStylesheet()
{
    //加载样式
    QFile file(":/res/style/default.css");
    file.open(QFile::ReadOnly);
    QString styleSheet =file.readAll();
    this->setStyleSheet(styleSheet);
    file.close();
}


void Application::newLocalConnection()
{
    QLocalSocket *socket=server->nextPendingConnection();
    if(!socket)
        return;

    //有新实例启动
    emit newInstanceBoot();
    delete socket;
}
